package com.xuhao.examai.scoring.infrastructure.persistence;

import com.xuhao.examai.scoring.domain.models.AnswerRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface AnswerRecordJpaRepository extends JpaRepository<AnswerRecord, Long> {

	List<AnswerRecord> findByExamRecordId(Long examRecordId);

	Optional<AnswerRecord> findByExamRecordIdAndQuestionId(Long examRecordId, Long questionId);

	List<AnswerRecord> findByQuestionId(Long questionId);

	@Query("SELECT ar FROM AnswerRecord ar WHERE ar.examRecordId = :examRecordId AND ar.isCorrect = true")
	List<AnswerRecord> findCorrectAnswersByExamRecordId(@Param("examRecordId") Long examRecordId);

	@Query("SELECT ar FROM AnswerRecord ar WHERE ar.examRecordId = :examRecordId AND ar.isCorrect = false")
	List<AnswerRecord> findIncorrectAnswersByExamRecordId(@Param("examRecordId") Long examRecordId);

	@Query("SELECT COUNT(ar) FROM AnswerRecord ar WHERE ar.questionId = :questionId AND ar.isCorrect = true")
	Long countCorrectAnswersByQuestionId(@Param("questionId") Long questionId);

	@Query("SELECT COUNT(ar) FROM AnswerRecord ar WHERE ar.questionId = :questionId")
	Long countTotalAnswersByQuestionId(@Param("questionId") Long questionId);

	@Modifying
	@Query("DELETE FROM AnswerRecord ar WHERE ar.examRecordId = :examRecordId")
	void deleteByExamRecordId(@Param("examRecordId") Long examRecordId);
}